# -*- coding: utf-8 -*-
'''
Created on Jun 18, 2013

@author: LONG HOANG GIANG
'''

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import pyLib
import json
import logging
import fnmatch
import re

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S')

class FunnyAppVN():
    
    
    def __init__(self, folder):
        
        self.source = "c:/Users/LONG HOANG GIANG/Downloads/APK/{0}/assets/www".format(folder)
        self.dest = "/longhoanggiang/funnyapp/{0}".format(pyLib.toLower(folder).replace(' ', '-'))
        pyLib.createIfNotExistsPath(self.dest)
        
    def listfiles(self):
        htmlfiles = {}
        for root, dirs, files in os.walk(self.source):
            for basename in files:
                if fnmatch.fnmatch(basename, "*.html"):
                    number = int(pyLib.extractText(r"(\d+)\.html", basename, 1))
                    htmlfiles[number] = basename
        sorted(htmlfiles, key=htmlfiles.get)
        return htmlfiles
        
    def process(self):
        data = []
        files = self.listfiles()
        for idx in files:
            name = "CHƯƠNG {0}".format(idx) if idx > 0 else "GIỚI THIỆU"
            path = pyLib.crc32unsigned(str(idx))
            print name, path
            htmlfile = self.source + "/" + files[idx]
            print htmlfile
            html = pyLib.file_get_content(htmlfile)
            html = re.sub(r"\n", "<br />", pyLib.cleanHTML(html).strip())
            html = "<b>{0}</b><br /><hr /><br />{1}".format(name, html)
            print html
            pyLib.gz_file_put_content(self.dest + "/files/" + path, json.dumps(html))
            data.append({'name': name, 'path': path})
            
        pyLib.gz_file_put_content(self.dest + "/data", pyLib.encryptCipher(json.dumps(data)))
            
                
    
if __name__ == '__main__':
    
    
    logging.info("start")
    a = FunnyAppVN("Mai mai la bao xa (hay)-")
    a.process()
    logging.info("finished")
    os._exit(1)